'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 战斗结束
 * @author agl
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var configUtil = require('../../../../util/configUtil');
var PlayerManager = require('../../../../libs/playerManager');
var taskService = require('../../../../services/taskService');
var roleService = require('../../../../services/roleService');
var arenaBattleRecordModel = require('../../../../models/arenaBattleRecordModel.js');
var arenaModel = require('../../../../models/arenaModel.js');
var arenaConf = require('../../../../config/arenaConf.js');
var rewardService = require('../../../../services/rewardService');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var battle_id = msg.record_id;
    var battle_result = msg.result;

    if (!battle_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var player_manager = new PlayerManager(role_id);
    var rival_player_manager;
    var rival_id;
    var battle_info;
    var rank_changed = 0;
    var curr_rank;
    var max_rank;
    var reward_list = [];
    var new_rank_reward = [];
    async.waterfall(
        [
            function (cb) {
                arenaModel.unLockRoles(role_id, cb);
            },
            function (cb) {
                arenaBattleRecordModel.findById(battle_id, cb);
            },
            function (info, cb) {
                if (!info) {
                    return next(null, {
                        code: Code.ARENA_INVALID_BATTLE_ID
                    });
                }

                battle_info = info;
                var now_tm = moment().unix();
                // if (now_tm - battle_info.create_tm > 300) {
                //     return next(null, {
                //         code: Code.ARENA_BATTLE_TIMEOUT
                //     });
                // }
                if (!!battle_info.battle_end) {
                    return next(null, {
                        code: Code.ARENA_BATTLE_ALREADY_END
                    });
                }

                rival_id = battle_info.def_role_id;

                cb();
            },
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['arena', 'build', 'soldier', 'role', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                rival_player_manager = new PlayerManager(rival_id);
                rival_player_manager.getModel(['arena'], cb);
            },
            function (cb) {
                var att_rank = battle_info.atk.rank;
                var def_rank = battle_info.def.rank;
                if (battle_result === 1) {
                    if (att_rank > def_rank) {
                        // 交换排名
                        rank_changed = att_rank - def_rank;
                        var arena_model = player_manager.arena;
                        var rival_arena_model = rival_player_manager.arena;
                        arena_model.rank = def_rank;
                        rival_arena_model.rank = att_rank;
                        // 设置最高排名
                        if (arena_model.rank < arena_model.max_rank) {
                            var old_max_rank = arena_model.max_rank;
                            arena_model.max_rank = arena_model.rank;
                            var new_max_rank = arena_model.max_rank;

                            new_rank_reward = arenaConf.getFirstRankReward(old_max_rank, new_max_rank);
                            rewardService.addRewardListToRole(player_manager, new_rank_reward, moduleType.MDL_ARENA, operationType.OPR_ARENA_MAX_RANK_REWARD);
                        }
                    }

                    // 胜利时统计胜利的次数
                    taskService.addArenaWinNum(player_manager);

                    // 固定奖励
                    reward_list = arenaConf.getFixedReward();
                    rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ARENA, operationType.OPR_ARENA_FIXED_RANK_REWARD);
                } else {
                    battle_result = -1;
                }

                arenaBattleRecordModel.setBattleResult(battle_id, battle_result, rank_changed, cb);
            },
            function (affect_info, cb) {
                if (affect_info.n !== 1) {
                    return next(null, {
                        code: Code.ARENA_BATTLE_SAVE_ERROR
                    });
                }
                if (rank_changed !== 0) {
                    player_manager.save(cb);
                } else {
                    cb();
                }
            },
            function (cb) {
                if (rank_changed !== 0) {
                    rival_player_manager.save(cb);
                } else {
                    cb();
                }
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    curr_rank: curr_rank,
                    max_rank: max_rank,
                    reward_list: reward_list,
                    new_rank_reward: new_rank_reward
                }
            });
        }
    );
};
